package com.fhyc.util;

import org.springframework.stereotype.Component;

import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;

@Component
public class Base64Util {
    public static String decodeToString(String encoded) {
        byte[] bytes = decode(encoded);
        return new String(bytes, StandardCharsets.UTF_8);
    }

    private static byte[] decode(String encoded) {
        char[] arrChars = encoded.toCharArray();
        arrChars = ensurePadding(arrChars);
        for (int i = 0; i < arrChars.length; i++) {
            if (arrChars[i] == '-') {
                arrChars[i] = '+';
            } else if (arrChars[i] == '_') {
                arrChars[i] = '/';
            }
        }

        String base64Text = new String(arrChars);
        return DatatypeConverter.parseBase64Binary(base64Text);
    }

    private static char[] ensurePadding(char[] chars) {
        char[] result = chars;
        int paddingcount = 0;
        int remainder = chars.length % 4;
        if (remainder == 2 || remainder == 3) {
            paddingcount = 4 - remainder;
        }
        if (paddingcount > 0) {
            result = new char[chars.length + paddingcount];
            System.arraycopy(chars, 0, result, 0, chars.length);
            for (int i = 0; i < paddingcount; ++i) {
                result[chars.length + i] = '=';
            }
        }
        return result;
    }

}
